<?php

namespace App\Workerman;

use App\Jobs\AddPkScore;
use App\Models\ScoreLogs;
use App\Models\User;
use Carbon\Carbon;
use GatewayWorker\Lib\Gateway;
use Illuminate\Support\Facades\Log;
use Workerman\Worker;

class Events
{
    /**
     * 游戏名称
     */
    const GAME_NAME = 'pk';

    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     *
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        $msg = ['type' => 'connected', 'time' => date('Y-m-d H:i:s')];
        // Helper::log('onConnect', $client_id, $msg);
        Gateway::sendToCurrentClient(json_encode($msg));
    }

    /**
     * 当客户端发来消息时触发
     *
     * @param int $client_id 连接id
     * @param mixed $message 具体消息
     */
    public static function onMessage($client_id, $message)
    {
        $message_data = json_decode($message, true);

        if (! $message_data) {
            return;
        }

        $uid = $message_data['uid'] ?? 0;
        $isRobot = (int) ($message_data['isRobot'] ?? 0);
        $pk_user_id = $isRobot ? 0 : ($message_data['pk_user_id'] ?? 0);
        $headurl = $message_data['image'] ?? 0;
        $nickname = $message_data['nickname'] ?? 0;
        $roomId = $message_data['roomId'] ?? 0;
        $num = $message_data['num'] ?? 0;
        $qid = $message_data['qid'] ?? 0;
        $reply = $message_data['reply'] ?? 0;
        $isright = $message_data['isright'] ?? 0;
        $score = $message_data['score'] ?? 0;
        $sort = $message_data['sort'] ?? 0;
        $robotright = $message_data['robotright'] ?? 0;
        $answerlogs = $message_data['answerlogs'] ?? 0;
        $isWin = (int) ($message_data['isWin'] ?? 0);

        switch ($message_data['gameType']) {
            // pk标准接口
            case 'pk_std':
                switch ($message_data['type']) {
                    // 随机匹配
                    case 'match':
                        // 规定两个匹配
                        $number = 2;

                        $match = new Match(self::GAME_NAME);
                        $userData = ['uid' => $uid, 'nickname' => $nickname, 'headurl' => $headurl];
                        $ret = $match->match($client_id, $userData);
                        if ($ret['code'] == 0) {
                            // 匹配成功
                            $data = [
                                'number'   => $number,
                                'roomId'   => $ret['roomId'],
                                'userData' => $ret['userData'],
                            ];

                            $userType = 0;
                            foreach ($ret['client_array'] as $value) {
                                $data['userData'][$value]['userType'] = $userType;
                                Gateway::updateSession($value, ['userType' => $userType]);
                                $userType++;
                            }
                            $msg = ['code' => 0, 'type' => 'matchSuccess', 'data' => $data];
                            foreach ($ret['client_array'] as $value) {
                                Gateway::sendToClient($value, json_encode($msg));
                            }
                        } elseif ($ret['code'] == 1 || $ret['code'] == 2) {
                            // 匹配中
                            $msg = ['code' => 1, 'type' => 'matching', 'data' => ['number' => $number]];
                            Gateway::sendToClient($client_id, json_encode($msg));
                        } else {
                            // 匹配失败
                            $msg = ['code' => -3, 'type' => 'matchFailed', 'data' => []];
                            Gateway::sendToClient($client_id, json_encode($msg));
                        }

                        break;

                    // 退出匹配
                    case 'quitMatch':
                        $match = new Match(self::GAME_NAME);
                        $match->logout($client_id);
                        $msg = ['code' => 0, 'type' => 'quitMatchSuccess'];
                        Gateway::sendToClient($client_id, json_encode($msg));
                        break;

                    // 加入房间
                    case 'joinRoom':
                        if (! $roomId || empty($roomId)) {
                            $msg = ['code' => -1, 'type' => 'roomId Error'];
                            Gateway::sendToClient($client_id, json_encode($msg));
                            return;
                        }
                        $userCount = Gateway::getClientCountByGroup($roomId);

                        if ($userCount >= 2) {
                            // 房间用户已满
                            $msg = ['code' => -2, 'type' => 'roomFilled'];
                            Gateway::sendToClient($client_id, json_encode($msg));
                        } else {
                            // 进房间前check
                            $groupSession = Gateway::getClientSessionsByGroup($roomId);
                            $res = Helper::joinRoomCheck($groupSession, $uid);
                            if (! $res) {
                                $msg = ['code' => -3, 'type' => 'joinFailed'];
                                Gateway::sendToClient($client_id, json_encode($msg));
                                return;
                            }

                            //加入房间
                            Gateway::joinGroup($client_id, $roomId);
                            if (isset($message_data['userType']) && ! empty($message_data['userType'])) {
                                Gateway::updateSession($client_id, ['roomId' => $roomId, 'uid' => $uid, 'lock' => 0, 'gameStart' => 0, 'userType' => $message_data['userType']]);
                            } else {
                                Gateway::updateSession($client_id, ['roomId' => $roomId, 'uid' => $uid, 'lock' => 0, 'gameStart' => 0]);
                            }

                            $groupSession = Gateway::getClientSessionsByGroup($roomId);
                            $msg = ['code' => 1, 'type' => 'joinSuccess', 'userCount' => $userCount];
                            $userCount = Gateway::getClientCountByGroup($roomId);
                            if ($userCount == 2) {
                                //加锁
                                $instance = RedisManager::getRedisInstance();
                                $redis = $instance->getRedisConnect();
                                $key = $roomId . '_joinRoom_lock';
                                $lock = $redis->get($key);
                                if ($lock && $lock == 1) {
                                    break;
                                } else {
                                    $lock = $redis->setex($key, 3, 1);
                                    //如果加入玩家后,当前链接正好2人,则通知双方,锁住房间
                                    $groupcids = Gateway::getClientIdListByGroup($roomId);
                                    foreach ($groupcids as $key => $value) {
                                        Gateway::updateSession($value, ['lock' => 1]);
                                    }
                                    $msg = ['code' => 3, 'type' => 'joinRoomByPK', 'userCount' => $userCount];
                                    Gateway::sendToGroup($roomId, json_encode($msg));
                                    //Gateway::sendToClient($client_id,json_encode($msg));

                                    //退出重新进，将当前题目、状态给客户端
                                    $instance = RedisManager::getRedisInstance();
                                    $redis = $instance->getRedisConnect();
                                    $key1 = $roomId . '_data';
                                    $key2 = $roomId . '_config';
                                    $data = $redis->get($key1);
                                    $config = $redis->get($key2);
                                    if (! empty($data) && ! empty($config)) {
                                        $mssg = ['code' => 4, 'type' => 'joinRoomAgain', 'data' => ['questions' => json_decode($data), 'config' => json_decode($config)]];
                                        Gateway::sendToCurrentClient(json_encode($mssg));
                                    }
                                    return;
                                }
                            }
                        }
                        break;

                    // 退出房间
                    case 'quitRoom':
                        if (! $roomId || empty($roomId)) {
                            $msg = ['code' => -1, 'type' => 'dataError'];
                            Gateway::sendToClient($client_id, json_encode($msg));
                            return;
                        }
                        $roomCids = Gateway::getClientIdListByGroup($roomId);
                        Gateway::leaveGroup($client_id, $roomId);
                        //Gateway::ungroup($roomId);
                        //如果加入玩家后,当前链接正好2人,则通知双方,锁住房间
                        $groupcids = Gateway::getClientIdListByGroup($roomId);
                        foreach ($groupcids as $key => $value) {
                            Gateway::updateSession($value, ['lock' => 0]);
                        }
                        $msg = ['code' => 1, 'type' => 'quitSuccess', 'uid' => $uid];
                        foreach ($roomCids as $key => $value) {
                            Gateway::sendToClient($value, json_encode($msg));
                        }
                        break;

                    // 游戏
                    case 'game':
                        $roomCount = Gateway::getClientIdCountByGroup($roomId);
                        $roomMessage = Gateway::getClientSessionsByGroup($roomId);
                        $roomCids = array_keys($roomMessage);

                        switch ($message_data['gameStatus']) {
                            case 'getQuestion':
                                if ($roomCount != 2) {
                                    $msg = ['code' => -2, 'type' => 'numberError'];
                                    Gateway::sendToGroup($roomId, json_encode($msg));
                                } else {
                                    if ($_SESSION['gameStart'] == 0) {
                                        //加锁
                                        $instance = RedisManager::getRedisInstance();
                                        $redis = $instance->getRedisConnect();
                                        $key = $roomId . '_' . $client_id . '_lock';
                                        $lock = $redis->get($key);
                                        if ($lock && $lock == 1) {
                                            $msg = ['code' => -1, 'type' => 'lock'];
                                            Gateway::sendToClient($client_id, json_encode($msg));
                                            break;
                                        } else {
                                            $lock = $redis->setex($key, 5, 1);

                                            $questions = Helper::getQuestions();

                                            if ($questions) {
                                                $config = ['current' => 1, 'count' => count($questions), 'curtime' => time()];
                                                $instance = RedisManager::getRedisInstance();
                                                $redis = $instance->getRedisConnect();
                                                $expire = 3600;
                                                $redis->setex($roomId . '_data', $expire, json_encode($questions));
                                                $redis->setex($roomId . '_config', $expire, json_encode($config));

                                                $msg = ['code' => 0, 'type' => 'answerDetail', 'data' => $questions, 'config' => $config];
                                                Gateway::sendToGroup($roomId, json_encode($msg));

                                                // 设置房间玩家答题状态
                                                foreach ($roomCids as $key => $value) {
                                                    Gateway::updateSession($value, ['gameStart' => 1]);
                                                }
                                            } else {
                                                Log::info('未获取到题目', $questions);
                                            }
                                        }
                                    } else {
                                        // 单独发题
                                        $instance = RedisManager::getRedisInstance();
                                        $redis = $instance->getRedisConnect();
                                        $key1 = $roomId . '_data';
                                        $key2 = $roomId . '_config';
                                        $data = $redis->get($key1);
                                        $config = $redis->get($key2);
                                        $msg = ['code' => 0, 'type' => 'answerDetail', 'data' => json_decode($data), 'config' => json_decode($config)];
                                        Gateway::sendToClient($client_id, json_encode($msg));
                                    }
                                }

                                break;
                            case 'post':
                                $roomMessage = Gateway::getClientSessionsByGroup($roomId);
                                $roomCids = array_keys($roomMessage);

                                // 更新答题状态
                                Gateway::updateSession($client_id, ['postStatus' => 1]);

                                // 倒计时未结束双方答题完成
                                foreach ($roomCids as $value) {
                                    if ($value == $client_id) {
                                        $postStatus1 = 1;

                                        $msg = ['code' => 0, 'type' => 'myPostResult', 'is_right' => $isright, 'ranswer' => $reply, 'score' => $score];
                                        Gateway::sendToClient($value, json_encode($msg));
                                    } else {
                                        $postStatus2 = isset(Gateway::getSession($value)['postStatus']) ? Gateway::getSession($value)['postStatus'] : 0;

                                        $msg = ['code' => 1, 'type' => 'otherPostResult', 'is_right' => $isright, 'ranswer' => $reply, 'score' => $score];
                                        Gateway::sendToClient($value, json_encode($msg));
                                    }
                                }

                                if ($roomCount == 2) {
                                    if ($postStatus1 == 1 && $postStatus2 == 1 && $sort < $num) {
                                        $instance = RedisManager::getRedisInstance();
                                        $redis = $instance->getRedisConnect();
                                        $expire = ceil(3600 * (($num - $sort + 1) / $num));
                                        $config = ['current' => $sort + 1, 'count' => $num, 'curtime' => time()];
                                        $redis->setex($roomId . '_config', $expire, json_encode($config));

                                        foreach ($roomCids as $key => $value) {
                                            Gateway::updateSession($value, ['postStatus' => 0]);
                                        }
                                        $msg = ['code' => 3, 'type' => 'postSuccess', 'config' => $config];
                                        Gateway::sendToGroup($roomId, json_encode($msg));
                                    }
                                } else {
                                    $instance = RedisManager::getRedisInstance();
                                    $redis = $instance->getRedisConnect();
                                    $expire = ceil(3600 * (($num - $sort + 1) / $num));
                                    $config = ['current' => $sort + 1, 'count' => $num, 'curtime' => time()];
                                    $redis->setex($roomId . '_config', $expire, json_encode($config));

                                    foreach ($roomCids as $key => $value) {
                                        Gateway::updateSession($value, ['postStatus' => 0]);
                                    }
                                    $msg = ['code' => 3, 'type' => 'postSuccess', 'config' => $config];
                                    Gateway::sendToGroup($roomId, json_encode($msg));
                                }

                                break;
                        }
                        break;

                    // ping
                    case 'ping':
                        $new_message = ['type' => 'pong'];
                        Gateway::sendToCurrentClient(json_encode($new_message));
                        break;
                }
                break;
            //机器人标准接口
            case 'single_std':
                switch ($message_data['type']) {
                    // 加入房间
                    case 'joinRoom':
                        if (! $roomId || empty($roomId)) {
                            $msg = ['code' => -1, 'type' => 'roomError'];
                            Gateway::sendToClient($client_id, json_encode($msg));
                            return;
                        }
                        // 进房间前check
                        $groupSession = Gateway::getClientSessionsByGroup($roomId);
                        $res = Helper::joinRoomCheck($groupSession, $uid);
                        if (! $res) {
                            $msg = ['code' => -3, 'type' => 'joinFailed'];
                            Gateway::sendToClient($client_id, json_encode($msg));
                            return;
                        }

                        // 加入房间
                        Gateway::joinGroup($client_id, $roomId);

                        $robot = Helper::getRobot();

                        if ($robot) {
                            $robotId = $robot['id'];
                            $robotHeader = $robot['img'];
                            $robotName = $robot['name'];
                            $robotright = $robot['right'];

                            Gateway::setSession($client_id, ['roomId' => $roomId, 'uid' => $uid, 'userType' => 0, 'lock' => 1, 'to_uid' => $robotId, 'robotHeader' => $robotHeader, 'robotName' => $robotName, 'robotright' => $robotright]); //userType 玩家状态 主机传0 其他玩家传1
                            $msg = ['code' => 2, 'type' => 'joinRoomComplete', 'data' => ['uid' => $uid, 'robotId' => $robotId, 'robotHeader' => $robotHeader, 'robotName' => $robotName, 'robotright' => $robotright], 'userCount' => 2];
                            Gateway::sendToClient($client_id, json_encode($msg));
                        } else {
                            $msg = ['code' => -1, 'type' => 'error_reboot'];
                            Gateway::sendToClient($client_id, json_encode($msg));
                        }

                        break;
                    case 'quitRoom':
                        if (! $roomId || empty($roomId)) {
                            $msg = ['code' => -1, 'type' => 'dataError'];
                            Gateway::sendToClient($client_id, json_encode($msg));
                            return;
                        }
                        //Gateway::ungroup($roomId);
                        Gateway::leaveGroup($client_id, $roomId);
                        Gateway::updateSession($client_id, ['lock' => 0]);
                        $msg = ['code' => 1, 'type' => 'quitSuccess', 'uid' => $uid];
                        Gateway::sendToClient($client_id, json_encode($msg));
                        break;
                    case 'game':
                        switch ($message_data['gameStatus']) {
                            case 'getQuestion':
                                $questions = Helper::getQuestions();

                                if ($questions) {
                                    $config = ['current' => 1, 'count' => count($questions)];
                                    $instance = RedisManager::getRedisInstance();
                                    $redis = $instance->getRedisConnect();
                                    $expire = 3600;
                                    $redis->setex($roomId . '_data', $expire, json_encode($questions));
                                    $redis->setex($roomId . '_config', $expire, json_encode($config));
                                    $robotArr = [];
                                    //$answerlogs = json_decode($answerlogs);
                                    $new = explode('@', $answerlogs);
                                    foreach ($questions as $key => $value) {

                                        if ($value['time'] > 0) {
                                            // 机器人 2-6 秒内答题
                                            $aTime = rand(2, 6); // rand(1, $value['time']);
                                        }
                                        if (in_array($key, $new)) {
                                            foreach ($value['options'] as $k => $v) {
                                                if ($v['isright'] == 1) {
                                                    $robotArr[$value['id']]['answerId'] = $v['id'];
                                                    $robotArr[$value['id']]['answerTime'] = $aTime;
                                                }
                                            }
                                        } else {
                                            foreach ($value['options'] as $k => $v) {
                                                if ($v['isright'] != 1) {
                                                    $robotArr[$value['id']]['answerId'] = $v['id'];
                                                    $robotArr[$value['id']]['answerTime'] = $aTime;
                                                }
                                            }
                                        }
                                    }

                                    // 获取机器人答题情况
                                    // $robotArr = Helper::robotAnswerData($questions);

                                    $msg = ['code' => 0, 'type' => 'answerDetail', 'data' => $questions, 'robotArr' => $robotArr, 'config' => $config];
                                } else {
                                    $msg = ['code' => -1, 'type' => '错误信息', 'data' => $questions];
                                }
                                Gateway::sendToClient($client_id, json_encode($msg));

                                break;
                            case 'post':
                                //提交答题
                                $instance = RedisManager::getRedisInstance();
                                $redis = $instance->getRedisConnect();
                                $expire = ceil(3600 * (($num - $sort + 1) / $num));
                                $config = ['current' => $sort + 1, 'count' => $num, 'curtime' => time()];
                                $redis->setex($roomId . '_config', $expire, json_encode($config));

                                $msg = ['code' => 0, 'type' => 'postSuccess', 'is_right' => $isright, 'ranswer' => $reply, 'config' => $config];
                                Gateway::sendToClient($client_id, json_encode($msg));

                                break;

                            case 'ping':
                                $msg = ['code' => 0, 'type' => 'redis', 'config' => 'ceshi'];
                                Gateway::sendToClient($client_id, json_encode($msg));
                                break;
                        }
                        break;
                }
                break;
            //好友邀请标准接口
            case 'invite_std':
                switch ($message_data['type']) {
                    case 'joinRoom':
                        if (! $roomId || empty($roomId)) {
                            $msg = ['code' => -1, 'type' => 'roomError'];
                            Gateway::sendToClient($client_id, json_encode($msg));
                            return;
                        }
                        $userCount = Gateway::getClientCountByGroup($roomId);

                        if ($userCount >= 2) {
                            //房间用户已满,获取房间用户信息
                            $groupSession = Gateway::getClientSessionsByGroup($roomId);
                            $msg = ['code' => -2, 'type' => 'roomFilled', 'data' => $groupSession];
                            Gateway::sendToClient($client_id, json_encode($msg));
                        } else {
                            //进房间前check
                            $groupSession = Gateway::getClientSessionsByGroup($roomId);
                            list($res, $res1) = Helper::joinRoomCheckv2($groupSession, $uid);
                            if (! $res) {
                                if (! empty($res1) && $res1 != 0) {
                                    $msg = ['code' => -3, 'type' => 'joinFailed', 'userData' => $res1];
                                } else {
                                    $msg = ['code' => -3, 'type' => 'joinFailed'];
                                }
                                Gateway::sendToClient($client_id, json_encode($msg));
                                return;
                            }

                            if ($userCount == 0 && $message_data['userType'] == 0) {
                                //加入房间
                                Gateway::joinGroup($client_id, $roomId);
                                Gateway::updateSession($client_id, ['roomId' => $roomId, 'uid' => $uid, 'headurl' => $headurl, 'nickname' => $nickname, 'lock' => 0, 'gameStart' => 0, 'userType' => $message_data['userType'], 'inviteTime' => time(), 'isPk' => 0]);

                                $msg = ['code' => 1, 'type' => 'joinSuccess', 'userCount' => $userCount + 1];
                                Gateway::sendToCurrentClient(json_encode($msg));
                                return;
                            } elseif ($userCount == 1) {
                                //加入房间
                                Gateway::joinGroup($client_id, $roomId);
                                Gateway::updateSession($client_id, ['roomId' => $roomId, 'uid' => $uid, 'headurl' => $headurl, 'nickname' => $nickname, 'lock' => 0, 'gameStart' => 0, 'userType' => $message_data['userType'], 'isPk' => 1]);

                                //获取房间用户信息
                                $userData = array();
                                $from_uid = 0;
                                $to_uid = 0;
                                $isPks = 0;
                                $inviteTime = 0;
                                $roomUserData = Gateway::getClientSessionsByGroup($roomId);
                                foreach ($roomUserData as $key => $value) {
                                    if ($value['userType'] == 0) {
                                        $from_uid = $value['uid'];
                                        $inviteTime = $value['inviteTime'] ?? 0;
                                    } else {
                                        $to_uid = $value['uid'];
                                    }
                                    if ($value['isPk'] == 1) {
                                        $isPks++;
                                    }

                                    $userData[$key]['uid'] = $value['uid'];
                                    $userData[$key]['headurl'] = $value['headurl'];
                                    $userData[$key]['nickname'] = $value['nickname'];
                                    $userData[$key]['userType'] = $value['userType'];
                                }

                                //退出重新进，将当前题目、状态给客户端
                                if ($isPks == 2) {
                                    $mssg = ['code' => 4, 'type' => 'joinRoomAgain', 'userCount' => $userCount + 1, 'userData' => $userData];
                                    Gateway::sendToCurrentClient(json_encode($mssg));
                                } else {
                                    $msg = ['code' => 2, 'type' => 'joinRoomWithPerson', 'userCount' => $userCount + 1, 'userData' => $userData];
                                    Gateway::sendToGroup($roomId, json_encode($msg));
                                }

                                //锁住房间
                                $groupcids = Gateway::getClientIdListByGroup($roomId);
                                foreach ($groupcids as $key => $value) {
                                    Gateway::updateSession($value, ['lock' => 1, 'inviteTime' => $inviteTime, 'isPk' => 1, 'from_uid' => $from_uid, 'to_uid' => $to_uid, 'userData' => $userData]);
                                }
                                return;
                            } else {
                                //房间失效
                                $msg = ['code' => -4, 'type' => 'roomLose'];
                                Gateway::sendToCurrentClient(json_encode($msg));
                                return;
                            }
                        }
                        break;
                    case 'quitRoom':
                        if (! $roomId || empty($roomId)) {
                            $msg = ['code' => -1, 'type' => 'dataError'];
                            Gateway::sendToClient($client_id, json_encode($msg));
                            return;
                        }
                        $userCount = Gateway::getClientCountByGroup($roomId);
                        $roomCids = Gateway::getClientIdListByGroup($roomId);
                        /*if($userCount == 1){
                            Gateway::ungroup($roomId);
                        }else{
                            Gateway::leaveGroup($client_id,$roomId);
                        }*/
                        Gateway::leaveGroup($client_id, $roomId);
                        //如果加入玩家后,当前链接正好2人,则通知双方,锁住房间
                        $groupcids = Gateway::getClientIdListByGroup($roomId);
                        foreach ($groupcids as $key => $value) {
                            Gateway::updateSession($value, ['lock' => 0]);
                        }
                        $msg = ['code' => 1, 'type' => 'quitSuccess', 'uid' => $uid];
                        foreach ($roomCids as $key => $value) {
                            Gateway::sendToClient($value, json_encode($msg));
                        }
                        break;
                    case 'getInviteStatus':
                        if (! $roomId || empty($roomId)) {
                            $msg = ['code' => -1, 'type' => 'dataError'];
                            //记录日志
                            Helper::log('returnToClient', $client_id, $msg);
                            Gateway::sendToClient($client_id, json_encode($msg));
                            return;
                        }

                        //获取房间用户信息
                        $userData = array();
                        $from_uid = 0;
                        $to_uid = 0;
                        $Arr = array();
                        $roomUserData = Gateway::getClientSessionsByGroup($roomId);
                        //记录日志
                        Helper::log('roomUserData', $client_id, $roomUserData);
                        foreach ($roomUserData as $key => $value) {
                            $userData[$key]['uid'] = isset($value['uid']) ? $value['uid'] : '';
                            $userData[$key]['headurl'] = isset($value['headurl']) ? $value['headurl'] : '';
                            $userData[$key]['nickname'] = isset($value['nickname']) ? $value['nickname'] : '';
                            $userData[$key]['userType'] = isset($value['userType']) ? $value['userType'] : '';
                            $userData[$key]['from_uid'] = isset($value['from_uid']) ? $value['from_uid'] : '';
                            $userData[$key]['to_uid'] = isset($value['to_uid']) ? $value['to_uid'] : '';
                            $from_uid = isset($value['from_uid']) ? $value['from_uid'] : 0;
                            $to_uid = isset($value['to_uid']) ? $value['to_uid'] : 0;
                            if (isset($value['inviteTime'])) {
                                $Arr['inviteTime'] = $value['inviteTime'];
                                $Arr['isPk'] = $value['isPk'];
                            }
                        }
                        //记录日志
                        Helper::log('foreachroomUserData', $client_id, $roomUserData);

                        $inviteStatus = 1;
                        $ret = array();
                        if (isset($Arr['isPk']) && $Arr['isPk'] == 1) {
                            $inviteStatus = 2;
                            $remain = $Arr['inviteTime'] + 300 - time();;
                            $remain = $remain >= 0 ? $remain : 0;

                            //断线重连
                            if ($from_uid != 0 && $to_uid != 0) {
                                if ($from_uid == $uid || $to_uid == $uid) {
                                    if ($uid == $to_uid) {
                                        $userType = 1;
                                    } elseif ($uid == $from_uid) {
                                        $userType = 0;
                                    } else {
                                        $inviteStatus = 2;
                                        $ret = ['inviteStatus' => $inviteStatus, 'remain' => $remain, 'userData' => $userData];
                                        $msg = ['code' => $inviteStatus, 'type' => 'getInviteStatusSuccess', 'data' => $ret];

                                        //记录日志
                                        Helper::log('returnToClient', $client_id, $msg);
                                        Gateway::sendToClient($client_id, json_encode($msg));
                                        break;
                                    }
                                    $inviteStatus = 4;
                                    $ret = ['inviteStatus' => $inviteStatus, 'remain' => $remain, 'userData' => $userData, 'userType' => $userType];
                                    $msg = ['code' => $inviteStatus, 'type' => 'getInviteStatusSuccess', 'data' => $ret];

                                    //记录日志
                                    Helper::log('returnToClient', $client_id, $msg);
                                    Gateway::sendToClient($client_id, json_encode($msg));
                                    break;
                                } else {
                                    $inviteStatus = 2;
                                    $ret = ['inviteStatus' => $inviteStatus, 'remain' => $remain, 'userData' => $userData];
                                    $msg = ['code' => $inviteStatus, 'type' => 'getInviteStatusSuccess', 'data' => $ret];

                                    //记录日志
                                    Helper::log('returnToClient', $client_id, $msg);
                                    Gateway::sendToClient($client_id, json_encode($msg));
                                    break;
                                }
                            }
                        } else if (isset($Arr['inviteTime']) && ($Arr['inviteTime'] + 300 >= time())) {
                            $remain = $Arr['inviteTime'] + 300 - time();
                        } else {
                            $remain = 0;
                            $inviteStatus = 0;
                        }
                        $ret = ['inviteStatus' => $inviteStatus, 'remain' => $remain, 'userData' => $userData];
                        $msg = ['code' => $inviteStatus, 'type' => 'getInviteStatusSuccess', 'data' => $ret];

                        //记录日志
                        Helper::log('returnToClient', $client_id, $msg);
                        Gateway::sendToClient($client_id, json_encode($msg));

                        break;
                }

            // 提交结果
            case 'submit':
                Gateway::updateSession($client_id, ['postStatus' => 0]);
                try {
                    AddPkScore::dispatch($roomId, $uid, $pk_user_id, $isWin);
                } catch (\Exception $e) {
                    Log::error('queue: ' . $e->getMessage(), $e->getTrace());
                }

                // // 今日已 PK 次数
                // $pkCount = ScoreLogs::query()
                //     ->where('is_win', '<', 3)
                //     ->where('user_id', $uid)
                //     ->where('created_at', '>', Carbon::today())
                //     ->count();
                //
                // // 获得能量（每天前 10 次，获胜得 5 能量，失败得 1 能量）
                // $score = 0;
                // if ($pkCount < 10) {
                //     $score = $isWin == 1 ? 5 : 1;
                //
                //     User::query()->where('id', $uid)->increment('score', $score);
                // }
                //
                // // 能量值日志
                // ScoreLogs::query()->insertOrIgnore([
                //     'room_id' => $roomId,
                //     'user_id' => $uid,
                //     'pk_user_id' => $pk_user_id,
                //     'is_robot' => $isRobot,
                //     'is_win' => $isWin, // 是否胜利 0 失败 1 胜利 2 平局 3 自测
                //     'score' => $score,
                //     'created_at' => now(),
                // ]);

                break;
        }
    }

    /**
     * 当用户断开连接时触发
     *
     * @param int $client_id 连接id
     */
    public static function onClose($client_id)
    {
        // 断开连接后退出匹配
        $match = new Match(self::GAME_NAME);
        $match->logout($client_id);
    }
}
